package com.tencent.wxcloudrun.service.business.fangdong;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tencent.wxcloudrun.config.CustomException;
import com.tencent.wxcloudrun.config.UserContext;
import com.tencent.wxcloudrun.dao.XHelpmateInfoMapper;
import com.tencent.wxcloudrun.pojo.bo.MediaInfo;
import com.tencent.wxcloudrun.pojo.bo.NoticeConstant;
import com.tencent.wxcloudrun.pojo.dto.req.SetHomeListToHelpMateReq;
import com.tencent.wxcloudrun.pojo.dto.resp.GetHelpMateListResp;
import com.tencent.wxcloudrun.pojo.dto.resp.GetLandlordInfoResp;
import com.tencent.wxcloudrun.pojo.dto.resp.HelpMateGetHomeListResp;
import com.tencent.wxcloudrun.pojo.po.XHelpmateInfo;
import com.tencent.wxcloudrun.pojo.po.XHouseInfo;
import com.tencent.wxcloudrun.pojo.po.XPersonInfo;
import com.tencent.wxcloudrun.service.XHelpmateInfoService;
import com.tencent.wxcloudrun.service.XHouseInfoService;
import com.tencent.wxcloudrun.service.XPersonInfoService;
import com.tencent.wxcloudrun.service.business.NoticeService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class HelpMateService {

    private static final String HELP_MATE = "helpMate_";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private XPersonInfoService xPersonInfoService;

    @Resource
    private XHelpmateInfoService xHelpmateInfoService;

    @Resource
    private XHelpmateInfoMapper xHelpmateInfoMapper;

    @Resource
    private XHouseInfoService xHouseInfoService;
    @Resource
    private NoticeService noticeService;
    @Resource
    private PersonService personService;

    public String getNum() {
        String openId = UserContext.getOpenId();
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, openId);
        List<XPersonInfo> allByPersonId = xPersonInfoService.list(xPersonInfoLambdaQueryWrapper);
        List<XPersonInfo> collect = allByPersonId.stream().filter(var -> "landlord".equals(var.getPersonType())).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            throw new CustomException("非房东不能进行此操作！");
        }
        String randomString;
        while (true) { // 要找到一个未被使用的编号
            randomString = RandomUtil.randomString("123456789", 6);
            String landId = redisTemplate.opsForValue().get(HELP_MATE + randomString);
            if (StrUtil.isBlank(landId)) {
                break;
            }
        }
        redisTemplate.opsForValue().set(HELP_MATE + randomString, openId, 5, TimeUnit.MINUTES);
        return randomString;
    }

    @Transactional(rollbackFor = Exception.class)
    public String beHelp(String num, String alias, String phone) {
        String landId = redisTemplate.opsForValue().get(HELP_MATE + num);
        if (StrUtil.isBlank(landId)) {
            throw new CustomException("编号已过期或不存在");
        }
        String openId = UserContext.getOpenId();
        // 一个人只能有一个助理身份
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getHelpmateId, openId);
        XHelpmateInfo oneByHelpmateId = xHelpmateInfoService.getOne(xHelpmateInfoLambdaQueryWrapper);
        if (ObjUtil.isNotNull(oneByHelpmateId)) {
            throw new CustomException("不能重复成为助理");
        }
        // 如果一个人是房东了，则他不能成为助理
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, openId);
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonType, "landlord");
        XPersonInfo oneByPersonId = xPersonInfoService.getOne(xPersonInfoLambdaQueryWrapper);
        if (ObjUtil.isNotNull(oneByPersonId) && StrUtil.isNotBlank(oneByPersonId.getPersonId())) {
            throw new CustomException("已是房东，不可成为助理！");
        }
        Date date = new Date();
        XHelpmateInfo xHelpmateInfo = new XHelpmateInfo();
        xHelpmateInfo.setLandlordId(landId);
        xHelpmateInfo.setHelpmateId(openId);
        xHelpmateInfo.setAlias(alias);
        xHelpmateInfo.setHelpPhone(phone);
        xHelpmateInfo.setCreateTime(date);
        xHelpmateInfoService.save(xHelpmateInfo);
        LambdaQueryWrapper<XPersonInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XPersonInfo::getPersonId, landId);
        queryWrapper.eq(XPersonInfo::getPersonType, "landlord");
        XPersonInfo landInfo = xPersonInfoService.getOne(queryWrapper);
        // 给助理发送通知
        noticeService.createNotice("helpmate", NoticeConstant.BE_HELP_TITLE,
                String.format(NoticeConstant.BE_HELP_CONTENT, landInfo.getCardName()));
        // 给房东发送通知
        noticeService.createNoticeByOpenid(landInfo.getPersonId(), "land", NoticeConstant.BE_HELP_LAND_TITLE,
                String.format(NoticeConstant.BE_HELP_LAND_CONTENT, xHelpmateInfo.getAlias()));
        // 要清除一下当前用户的redis中的身份信息
        redisTemplate.delete("identity_" + openId);
        // 调用此方法对身份信息进行初始化
        personService.isLandlord();
        return "成功成为助理";
    }

    public List<GetHelpMateListResp> getHelpMateList() {
        String openId = UserContext.getOpenId();
        List<GetHelpMateListResp> respList = new ArrayList<>();
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getLandlordId, openId);
        List<XHelpmateInfo> allByLandlordId = xHelpmateInfoService.list(xHelpmateInfoLambdaQueryWrapper);
        if (CollUtil.isEmpty(allByLandlordId)) {
            return respList;
        }
        for (XHelpmateInfo xHelpmateInfo : allByLandlordId) {
            GetHelpMateListResp getHelpMateListResp = new GetHelpMateListResp();
            getHelpMateListResp.setId(xHelpmateInfo.getHelpmateId());
            getHelpMateListResp.setAlias(xHelpmateInfo.getAlias());
            getHelpMateListResp.setTime(DateUtil.format(xHelpmateInfo.getCreateTime(), DatePattern.NORM_DATE_PATTERN));
            int num = 0;
            if (StrUtil.isNotBlank(xHelpmateInfo.getHouseList()) && !"[]".equals(xHelpmateInfo.getHouseList())) {
                List<String> stringList = JSON.parseArray(xHelpmateInfo.getHouseList(), String.class);
                num = stringList.size();
            }
            getHelpMateListResp.setNum("已管理" + num + "间房屋");
            respList.add(getHelpMateListResp);
        }
        return respList;
    }

    @Transactional(rollbackFor = Exception.class)
    public String delMate(String id) {
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getHelpmateId, id);
        XHelpmateInfo oneById = xHelpmateInfoService.getOne(xHelpmateInfoLambdaQueryWrapper);
        String openId = UserContext.getOpenId();
        if (!oneById.getLandlordId().equals(openId)) {
            throw new CustomException("非法删除助理");
        }
        xHelpmateInfoMapper.delete(xHelpmateInfoLambdaQueryWrapper);
        // 要清除一下当前用户的redis中的身份信息
        redisTemplate.delete("identity_" + oneById.getHelpmateId());
        // 调用此方法对身份信息进行初始化
        personService.isLandlord();
        return "成功删除";
    }

    @Transactional(rollbackFor = Exception.class)
    public String updateName(String id, String alias, String phone) {
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getHelpmateId, id);
        XHelpmateInfo xHelpmateInfo = new XHelpmateInfo();
        if (StrUtil.isNotBlank(alias)) {
            xHelpmateInfo.setAlias(alias);
        }
        if (StrUtil.isNotBlank(phone)) {
            xHelpmateInfo.setHelpPhone(phone);
        }
        xHelpmateInfoService.update(xHelpmateInfo, xHelpmateInfoLambdaQueryWrapper);
        return "修改成功";
    }

    public List<HelpMateGetHomeListResp> getHomeList(String id) {
        String openId = UserContext.getOpenId();
        LambdaQueryWrapper<XHouseInfo> xHouseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHouseInfoLambdaQueryWrapper.eq(XHouseInfo::getLandlordId, openId);
        List<XHouseInfo> houseInfoList = xHouseInfoService.list(xHouseInfoLambdaQueryWrapper);
        List<HelpMateGetHomeListResp> respList = new ArrayList<>();
        if (CollUtil.isEmpty(houseInfoList)) {
            return respList;
        }
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getHelpmateId, id);
        XHelpmateInfo one = xHelpmateInfoService.getOne(xHelpmateInfoLambdaQueryWrapper);
        List<String> stringList = new ArrayList<>();
        if (StrUtil.isNotBlank(one.getHouseList()) && !"[]".equals(one.getHouseList())) {
            stringList = JSON.parseArray(one.getHouseList(), String.class);
        }
        for (XHouseInfo houseInfo : houseInfoList) {
            HelpMateGetHomeListResp helpMateGetHomeListResp = new HelpMateGetHomeListResp();
            helpMateGetHomeListResp.setHomeId(houseInfo.getHouseId());
            if (houseInfo.getPicId() != null) {
                List<MediaInfo> mediaInfoList = JSON.parseArray(houseInfo.getPicId(), MediaInfo.class);
                List<MediaInfo> collect = mediaInfoList.stream()
                        .filter(var -> "jpeg".equalsIgnoreCase(HouseManageService.getLastPartAfterDot(var.getFileID())) ||
                                "jpg".equalsIgnoreCase(HouseManageService.getLastPartAfterDot(var.getFileID())) ||
                                "png".equalsIgnoreCase(HouseManageService.getLastPartAfterDot(var.getFileID())))
                        .collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    helpMateGetHomeListResp.setPic(collect.get(0).getFileID());
                }
            }
            helpMateGetHomeListResp.setTag("no");
            if (CollUtil.isNotEmpty(stringList) && stringList.contains(houseInfo.getHouseId())) {
                helpMateGetHomeListResp.setTag("yes");
            }
            helpMateGetHomeListResp.setTitle(houseInfo.getHouseName() + "_" + houseInfo.getFloor() + "楼_" + houseInfo.getArea() + "平米");
            helpMateGetHomeListResp.setDesc(houseInfo.getAddress());
            helpMateGetHomeListResp.setInfo(houseInfo.getMouthMoney().toPlainString());
            respList.add(helpMateGetHomeListResp);
        }
        return respList;
    }

    @Transactional(rollbackFor = Exception.class)
    public String setHomeListToHelpMate(SetHomeListToHelpMateReq req) {
        if (CollUtil.isEmpty(req.getHomeList())) {
            throw new CustomException("请先勾选房屋");
        }
        LambdaQueryWrapper<XHelpmateInfo> xHelpmateInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xHelpmateInfoLambdaQueryWrapper.eq(XHelpmateInfo::getHelpmateId, req.getId());
        XHelpmateInfo xHelpmateInfo = new XHelpmateInfo();
        xHelpmateInfo.setHouseList(JSON.toJSONString(req.getHomeList()));
        xHelpmateInfoService.update(xHelpmateInfo, xHelpmateInfoLambdaQueryWrapper);
        return "保存房屋权限成功";
    }

    /**
     * 助理查看房东信息
     */
    public GetLandlordInfoResp getLandlordInfo() {
        String openId = UserContext.getOpenId();

        // 查询助理信息
        LambdaQueryWrapper<XHelpmateInfo> helpmateQuery = new LambdaQueryWrapper<>();
        helpmateQuery.eq(XHelpmateInfo::getHelpmateId, openId);
        XHelpmateInfo helpmateInfo = xHelpmateInfoService.getOne(helpmateQuery);

        if (ObjUtil.isNull(helpmateInfo)) {
            throw new CustomException("当前无房东归属信息");
        }

        // 查询房东信息
        LambdaQueryWrapper<XPersonInfo> landlordQuery = new LambdaQueryWrapper<>();
        landlordQuery.eq(XPersonInfo::getPersonId, helpmateInfo.getLandlordId());
        landlordQuery.eq(XPersonInfo::getPersonType, "landlord");
        XPersonInfo landlordInfo = xPersonInfoService.getOne(landlordQuery);

        if (ObjUtil.isNull(landlordInfo)) {
            throw new CustomException("房东信息不存在");
        }

        GetLandlordInfoResp resp = new GetLandlordInfoResp();
        resp.setCardName(landlordInfo.getCardName());
        resp.setPhone(landlordInfo.getPhone());

        return resp;
    }

    /**
     * 助理取消与房东的绑定关系
     */
    @Transactional(rollbackFor = Exception.class)
    public String unbindLandlord() {
        String openId = UserContext.getOpenId();

        // 查询助理信息
        LambdaQueryWrapper<XHelpmateInfo> helpmateQuery = new LambdaQueryWrapper<>();
        helpmateQuery.eq(XHelpmateInfo::getHelpmateId, openId);
        XHelpmateInfo helpmateInfo = xHelpmateInfoService.getOne(helpmateQuery);

        if (ObjUtil.isNull(helpmateInfo)) {
            throw new CustomException("当前无房东归属信息");
        }

        // 删除绑定关系
        xHelpmateInfoService.remove(helpmateQuery);
        // 要清除一下当前用户的redis中的身份信息
        redisTemplate.delete("identity_" + openId);
        // 调用此方法对身份信息进行初始化
        personService.isLandlord();

        return "成功取消与房东的绑定关系";
    }
}
